package com.cgc.shop.service.impl;

import org.springframework.stereotype.Service;

import com.cgc.shop.model.Cart;
import com.cgc.shop.model.Orders;
import com.cgc.shop.model.Product;
import com.cgc.shop.service.OrdersService;
@Service("ordersService")
public class OrdersServiceImpl extends BaseServiceImpl<Orders> implements OrdersService {
	@Override
	public Orders productToOrders(Product product) {
		Orders orders = new Orders();
		orders.setName(product.getName());
		orders.setNumber(1);
		orders.setPrice(product.getPrice());
		orders.setProduct(product);
		return orders;
	}

	@Override
	public Cart addOrders(Product product, Cart cart) {
		boolean isInCart = false;
		for (Orders orders : cart.getOrderses()) {
			if (product.getId().equals(orders.getProduct().getId())) {
				//如果购物车中已存在该物品直接数量加1
				orders.setNumber(orders.getNumber() + 1);
				isInCart = true;
				break;
			}
		}
		//购物车中不存在该商品，则转化为订单添加到购物车中
		if (!isInCart) {
			Orders orders = productToOrders(product);
			orders.setCart(cart);
			cart.getOrderses().add(orders);
		}
		return cart;
	}
}
